//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  message,
  Table,
} from 'antd';
//import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AreaTreeList from '@/components/AsyncLoadingTreeList';

import AreaCreateForm from './AreaCreateForm'; //新增表单
import AreaUpdateForm from './AreaUpdateForm'; //修改表单
import AreaViewForm  from './AreaViewForm'; //查看表单

import styles from './AreaList.less';
import { getValue } from '@/utils/globalcommon';

const FormItem = Form.Item;
const { Option } = Select;


function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
  return totalList;
}
class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };
  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <Table
          rowKey={rowKey || 'id' || 'key'}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
        />
      </div>
    );
  }
}


/* eslint react/no-multi-comp:0 */
@connect(({ area, loading }) => ({
  area,
  loading: loading.models.area,
}))

@Form.create()
class AreaList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    viewModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    viewFormValues: {},
    reloadAreaTree: "",
    reloadAreaTreeUpdate: "",
    reloadAreaTreeDelete: "",
    addAreaTreeInfo: {},
    parentId: "",
  };

  columns = [

    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },{
      title: '地区ID',
      dataIndex: 'id',
      key: 'id',
    }
  ];


  componentDidMount() {
 
  }



  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,parentId } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
      parentid: parentId,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'area/get_area_list_by_parentid',
      payload: params,
    });
  };

  previewItem = id => {
    router.push(`/profile/basic/${id}`);
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'area/query_page_for_area',
      payload: {},
    });
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'area/query_page_for_area',
        payload: values,
      });
    });
  };


  handleModalVisible = (flag, record, reLoadCurrentTreeNode) => {
    this.setState({
      modalVisible: !!flag,
      addAreaTreeInfo: record || {},
      reloadAreaTree: reLoadCurrentTreeNode,
    });
  };

  handleUpdateModalVisible = (flag, record, reLoadCurrentTreeNodeUpdate) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {},
      reloadAreaTreeUpdate: reLoadCurrentTreeNodeUpdate,
    });
  };

  handleViewModalVisible = (flag, record) => {
    this.setState({
      viewModalVisible: !!flag,
      viewFormValues: record || {},
    });
  };

  handleAdd = async fields => {
    const { dispatch } = this.props;
    const { key, levelcode } = this.state.addAreaTreeInfo.props.dataRef;
    await dispatch({
      type: 'area/insert_for_area',
      payload: {
        name: fields.name,
        parentid: key,
        levelcode: levelcode,
        levels: fields.levels,
        icon: fields.icon,
        cls: fields.cls,
        leaf: fields.leaf,
        squences: fields.squences,
        enables: fields.enables,
        id: fields.id,
        systime: fields.systime,
      },
    });
    const { area: { recorddata } } = this.props;
    this.state.reloadAreaTree(recorddata.datarecord, this.state.addAreaTreeInfo.props.eventKey);
    message.success('添加成功');
    this.handleModalVisible();
  };


  handleDeleteRecord = (record, reLoadCurrentTreeNodeDelete) => {
    const { dispatch } = this.props;

    dispatch({
      type: 'area/delete_by_primarykey_for_area',
      payload: {
        recordid: record.props.dataRef.id,
      },
      callback:() => {
        this.setState({
          selectedRows: [],
        });
        reLoadCurrentTreeNodeDelete(record.props.eventKey);
      },
    });

    message.success('删除成功');

  };

  handleUpdate = async (areaTreeRecord, fields) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    await dispatch({
      type: 'area/update_for_area',
      payload: {
        name: fields.title,
        id: fields.id,
        parentid: fields.parentid,
        levelcode: fields.levelcode,
        icon: fields.icon,
        cls: fields.cls,
        leaf: fields.leaf,
        squences: fields.squences,
        levels: fields.levels,
        enables: fields.enables,
        systime: fields.systime,
      },
    });
    this.state.reloadAreaTreeUpdate(fields, areaTreeRecord.props.eventKey, areaTreeRecord.props.dataRef.parentid);
    message.success('修改成功');
    this.handleUpdateModalVisible();
  };

  checkedTreeChild = node => {
	const parentId = node.props.dataRef.key;
	const { dispatch } = this.props;
  	dispatch({
        type: 'area/get_area_list_by_parentid',
        payload: {
        	parentid: parentId,
        }
  	});
  	this.setState({
  		parentId,
  	})
  };
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
           <Col md={8} sm={24}>
		        <FormItem label="地区名称">
		        	{getFieldDecorator('name')(<Input placeholder="请选择" style={{ width: '100%' }} />)}
		    	</FormItem>
		    </Col>
		    <Col md={8} sm={24}>
		        <FormItem label="地区级别">
			        {getFieldDecorator('level')(
			    		<Select placeholder="请选择" style={{ width: '100%' }}>
						<Option value="1">一级</Option>
						<Option value="2">二级</Option>
						<Option value="3">三级</Option>
						<Option value="4">四级</Option>
				        </Select>
					)}
				</FormItem>
		    </Col>
    <Col md={8} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
        展开 <Icon type="down" />
        </a>
        </span>
        </Col>
        </Row>
        </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
		        <FormItem label="地区名称">
		        	{getFieldDecorator('name')(<Input placeholder="请选择" style={{ width: '100%' }} />)}
		    	</FormItem>
		    </Col>
		    <Col md={8} sm={24}>
		        <FormItem label="地区级别">
			        {getFieldDecorator('level')(
			    		<Select placeholder="请选择" style={{ width: '100%' }}>
						<Option value="1">一级</Option>
						<Option value="2">二级</Option>
						<Option value="3">三级</Option>
						<Option value="3">四级</Option>
				        </Select>
					)}
				</FormItem>
		    </Col>
    	</Row>
    <div style={{ overflow: 'hidden' }}>
<div style={{ marginBottom: 24 }}>
<Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>
        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
        收起 <Icon type="up" />
        </a>
        </div>
        </div>
        </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      area: { data, areaTree },
      loading,
    } = this.props;



    const { selectedRows, modalVisible, updateModalVisible, viewModalVisible, updateFormValues, viewFormValues } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    const viewMethods = {
      handleViewModalVisible: this.handleViewModalVisible
    };

    const parentRole = {
      dispatch: this.props.dispatch,
      checkedTreeChild: this.checkedTreeChild,
      handleModalVisible: this.handleModalVisible,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleDeleteRecord: this.handleDeleteRecord,
      handleViewModalVisible: this.handleViewModalVisible,
      rootNodeName: "地区",
      searchTreePlaceholder: "请选择地区",
      asyncLoadingTreeUrl: 'area/get_area_tree_by_parentid',
      updateTreeNodeBydragUrl: 'area/update_change_target_node_with_source_node',
    }

    return (
      <PageHeaderWrapper title="地区信息列表">
            <Card bordered={false}>
            <div className={styles.areatableList}>
            {/*<div className={styles.areatableListForm}>{this.renderForm()}</div>*/}
            <div className={styles.areatableListOperator}>
    </div>

    	{areaTree && Object.keys(areaTree).length ? (
        	<AreaTreeList {...parentRole} treeList={areaTree}/>
        ) : null}
        <StandardTable
        rowKey={"id"}
        selectedRows={selectedRows}
        loading={loading}
        data={data}
        columns={this.columns}
        onSelectRow={this.handleSelectRows}
        onChange={this.handleStandardTableChange}
        />
        </div>
        </Card>
        <AreaCreateForm {...parentMethods} modalVisible={modalVisible} />

        {updateFormValues && Object.keys(updateFormValues).length ? (
            <AreaUpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            />
        ) : null}

        {viewFormValues && Object.keys(viewFormValues).length ? (
            <AreaViewForm
            {...viewMethods}
            viewModalVisible={viewModalVisible}
            values={viewFormValues}
            />
        ) : null}

    </PageHeaderWrapper>
    );
  }
}

export default AreaList;
